package com.shuqing.download.engine.distribute.dispatch.assemble.strategy.easy;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.ListUtils;
import com.shuqing.download.engine.DownLoadHeader;
import com.shuqing.download.engine.constants.ActuatorEnum;
import com.shuqing.download.engine.distribute.dispatch.assemble.AbstractAssembleActuator;
import com.shuqing.download.engine.distribute.dispatch.assemble.AssembleContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangshuqing
 * @date 2023/2/23 10:19
 */
@Slf4j
@Component
public class EasyExcelExportActuator extends AbstractAssembleActuator {


    @Override
    public EasyExcelExportContext createAssembleContext() {
        return new EasyExcelExportContext();
    }

    @Override
    public void setExecuteExportContext(AssembleContext context) {
        EasyExcelExportContext exportContext=(EasyExcelExportContext)context;
        exportContext.setCurrSheetSize(0);
        //初始化header
        List<List<String>> easyHeaders = ListUtils.newArrayList();
        List<String> currHeader;
        for(DownLoadHeader header:context.getExportHeaders()){
            currHeader=new ArrayList<>();
            currHeader.add(header.getHeadName());
            easyHeaders.add(currHeader);
        }
        ExcelWriter excelWriter= EasyExcel.write(context.getFileAbsolutePath()).head(easyHeaders).build();
        exportContext.setExcelWriter(excelWriter);
        exportContext.createSheet();
    }

    @Override
    public void executeExport(AssembleContext context, List<List<Object>> dataLs, int pageNum) {
        log.info("下载任务{},开始执行写入第{}页操作>>>",context.getTaskId(),pageNum);
        EasyExcelExportContext easyContext=(EasyExcelExportContext)context;
        //数据条数
        int dataSize=dataLs.size();
        if(easyContext.getCurrSheetSize()+dataSize<=engineConfig.getMaxOnceSheetSize()){
            easyContext.writeSheet(dataLs);
        }else{
            int writeSize=engineConfig.getMaxOnceSheetSize()-easyContext.getCurrSheetSize();
            //剩余空间还可以写满
            if(writeSize>=dataSize){
                easyContext.writeSheet(dataLs);
            }else{
                //剩余空间不足以写满 ,正常一个sheet
                //第一部分写入部分 ,写完必定sheet满了
                List<List<Object>> firstData=dataLs.subList(0,writeSize);
                easyContext.writeSheet(firstData);
                //写入第二部分
                List<List<Object>> secondData=dataLs.subList(writeSize,dataSize);
                easyContext.createSheet();
                easyContext.writeSheet(secondData);
            }
        }
        log.info("下载任务{},结束第{}页操作<<<",context.getTaskId(),pageNum);
    }


    @Override
    public ActuatorEnum actuatorEnum() {
        return ActuatorEnum.ASSEMBLE_EASY_EXCEL;
    }
}
